/*
 * bloom.org 2005 copyright
 */
package org.nanhill.commons.math;

/**
 * @author alin
 */
public class Prime {

	/**
	 * @param n
	 * @return if n is a prime return true, else false
	 */
	public static boolean isPrime(int n) {
		// filte negative, zero, one
		if (1 >= n) {
			return false;
		}
		// 2 is a prime, stop filter
		if (2 == n) {
			return true;
		}
		// filter evens
		if (0 == n % 2) {
			return false;
		}
		// go on filting...
		for (int a = 3; a <= Math.sqrt(n); a += 2) {
			if (0 == n % a) {
				return false;
			}
		}
		// the rest is all prime, stop filting
		return true;
	}

	/**
	 * @param n 
	 * @return if n less than 1 return -1; else if n is a prime return 0; else
	 *         return the smallest gene.
	 */
	public static int getSmallestGene(int n) {
		if (1 >= n) {
			return -1;
		}
		// 2 is a prime
		if (2 == n) {
			return 0;
		}
		// filter even
		if (0 == n % 2) {
			return 2;
		}
		//
		for (int i = 3; i <= Math.sqrt(n); i += 2) {
			if (0 == n % i) {
				return i;
			}
		}
		// is prime
		return 0;
	}

}
